package com.tjp.eight.utils;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import com.tjp.eight.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2017/3/27.
 */

public class UpdateService extends Service {
    private String url = null;
    // 通知栏
    private NotificationManager updateNotificationManager = null;
    private Notification updateNotification = null;
    private String appName = null;
    private String fileName = null;
    private String updateDir = null;

    //通知栏跳转Intent

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 获取传值
        url = intent.getStringExtra("url");
        appName = "八秒视频";
        if (url != null) {
            fileName = intent.getStringExtra("filename");//url.substring(url.lastIndexOf("/") + 1)
            if (!fileName.endsWith(".apk")) {
                fileName = fileName + ".apk";
            }
            updateDir = "/sdcard/掌云/";//Environment.getDataDirectory() + "/data/" + this.getPackageName() + "/files/";
            Intent nullIntent = new Intent();
            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, nullIntent, 0);
            // 创建文件
            updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            updateNotification = new Notification();
            updateNotification.icon = R.mipmap.ic_launcher;
            updateNotification.contentView = new RemoteViews(this.getPackageName(), R.layout.content_view);//通知栏中进度布局
            updateNotification.flags = Notification.FLAG_AUTO_CANCEL;
            updateNotification.contentIntent = pendingIntent;
            updateNotificationManager.notify(101, updateNotification);
            //开启线程现在
            new Thread(new updateRunnable()).start();
        }
        return super.onStartCommand(intent, 0, 0);
    }

    private class updateRunnable implements Runnable {
        Message message = updateHandler.obtainMessage();

        public void run() {
            message.what = 0;
            try {
                long downloadSize = downloadUpdateFile(url);
                Log.i("cai", downloadSize / 1024 + "");
                if (downloadSize > 0) {
                    // 下载成功
                    updateHandler.sendMessage(message);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                message.what = 1;
                message.obj = ex.getMessage();
                // 下载失败
                updateHandler.sendMessage(message);
            }
        }
    }

    private Handler updateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    // 点击安装PendingIntent
                    Intent installIntent = new Intent(Intent.ACTION_VIEW);
                    //installIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED| Intent.FLAG_ACTIVITY_NEW_TASK);
                    installIntent.setDataAndType(Uri.fromFile(new File(updateDir, fileName)), "application/vnd.android.package-archive");
                    //getApplication().startActivity(installIntent);
//                    updateNotification.contentView.setViewVisibility(R.id.content_view_progress, View.GONE);
//                    updateNotification.contentView.setViewVisibility(R.id.content_view_tips, View.VISIBLE);
                    updateNotification.contentView.setTextViewText(R.id.content_view_text1, 100 + "%");
//                    updateNotification.contentView.setTextViewText(R.id.content_view_tips, "下载完成");
                    PendingIntent updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0);
                    updateNotification.defaults = Notification.DEFAULT_SOUND;// 铃声提醒
                    updateNotification.flags = Notification.FLAG_AUTO_CANCEL;
                    //updateNotification.setLatestEventInfo(UpdateService.this,appName, "下载完成,点击安装", updatePendingIntent);
                    updateNotification.contentIntent = updatePendingIntent;
                    updateNotificationManager.notify(101, updateNotification);
                    // 停止服务
                    stopSelf();
                    break;
                case 1:
                    Intent nullIntent = new Intent();
                    PendingIntent pendingIntent = PendingIntent.getActivity(UpdateService.this, 10, nullIntent, 0);
                    // 下载失败
                    updateNotification.contentView.setViewVisibility(R.id.content_view_progress, View.GONE);
                    updateNotification.contentView.setViewVisibility(R.id.content_view_tips, View.VISIBLE);
                    updateNotification.contentView.setTextViewText(R.id.content_view_tips, "下载失败!" + fileName);
                    updateNotification.flags = Notification.FLAG_AUTO_CANCEL;
                    updateNotification.contentIntent = pendingIntent;
                    updateNotificationManager.notify(101, updateNotification);
                    stopSelf();
                    break;
                default:
                    updateNotification.contentView.setViewVisibility(R.id.content_view_progress, View.GONE);
                    updateNotification.contentView.setViewVisibility(R.id.content_view_tips, View.VISIBLE);
                    updateNotification.contentView.setTextViewText(R.id.content_view_tips, "下载失败");
                    updateNotification.flags = Notification.FLAG_AUTO_CANCEL;
                    updateNotificationManager.notify(101, updateNotification);
                    stopSelf();
            }
        }
    };

    //下载
    @SuppressLint("WorldReadableFiles")
    public long downloadUpdateFile(String downloadUrl) throws Exception {
        int downloadCount = 0;
        int currentSize = 0;
        long totalSize = 0;
        int updateTotalSize = 0;

        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        File tmpFile = new File("/sdcard/八秒视频/");
        if (!tmpFile.exists()) {
            tmpFile.mkdir();
        }
        final File file = new File("/sdcard/八秒视频/" + fileName);
        try {
            URL url = new URL(downloadUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            if (currentSize > 0) {
                httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
            }
            httpConnection.setConnectTimeout(10000);
            httpConnection.setReadTimeout(20000);
            updateTotalSize = httpConnection.getContentLength();
            if (httpConnection.getResponseCode() == 404) {
                throw new Exception("fail!");
            }
            is = httpConnection.getInputStream();
            fos = new FileOutputStream(file);
            byte buffer[] = new byte[512];
            int readsize = 0;
            while ((readsize = is.read(buffer)) > 0) {
                fos.write(buffer, 0, readsize);
                totalSize += readsize;
                //为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
                if ((downloadCount == 0) || (int) (totalSize * 100 / updateTotalSize) - 10 > downloadCount) {
                    downloadCount += 10;
                    Intent nullIntent = new Intent();
                    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, nullIntent, 0);
                    updateNotification.contentIntent = pendingIntent;
                    updateNotification.contentView.setTextViewText(R.id.content_view_text1, downloadCount + "%");
                    updateNotification.contentView.setProgressBar(R.id.content_view_progress, 100, downloadCount, false);
                    updateNotificationManager.notify(101, updateNotification);
                }
            }
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
            if (is != null) {
                is.close();
            }
            if (fos != null) {
                fos.close();
            }
        }


        updateNotification.contentView.setTextViewText(R.id.content_view_text1, 100 + "%");
        updateNotification.contentView.setProgressBar(R.id.content_view_progress, 100, 100, false);
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        //installIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED| Intent.FLAG_ACTIVITY_NEW_TASK);
        installIntent.setDataAndType(Uri.fromFile(new File(updateDir, fileName)), "application/vnd.android.package-archive");
        PendingIntent updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0);
        updateNotification.contentIntent = updatePendingIntent;
        updateNotificationManager.notify(101, updateNotification);
        openFile(this, file);
        return totalSize;
    }

    private void openFile(Context context, File file) {
        updateNotificationManager.cancel(101);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}